package com.baseframe.gateway.filter;

import org.springframework.boot.autoconfigure.jersey.JerseyProperties;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsProcessor;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;


/**
 * 解决跨域问题 定义web过滤器
 */
@Component
public class BaseCorsFilter implements WebFilter , Ordered {

    private static final String ALLOWED_HEADERS = "*";
    private static final String ALLOWED_METHODS = "*";//支持跨域发方法
    private static final String ALLOWED_ORIGIN = "*";//来源
    private static final String ALLOWED_EXPOSE = "*";
    private static final String MAX_AGE = "18000L";//最大时效

    @Override
    @NonNull
    public Mono<Void> filter(ServerWebExchange exchange,@NonNull WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (CorsUtils.isCorsRequest(request)){
            ServerHttpResponse response = exchange.getResponse();
            HttpHeaders headers = response.getHeaders();
            //设置跨域头
            headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS);
            headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
            headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
            headers.add("Access-Control-Expose-Headers", ALLOWED_EXPOSE);
            headers.add("Access-Control-Max-Age", MAX_AGE);
            headers.add("Access-Control-Allow-Credentials", "true");
            //判断是不是 OPTIONS 请求 一般该请求用来询问是否支持跨域
            if (request.getMethod() == HttpMethod.OPTIONS) {
                response.setStatusCode(HttpStatus.OK);
                return Mono.empty();
            }
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
